package sb.simple.multi_sql_source.configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "sb.simple.multi_sql_source.login.dao", sqlSessionTemplateRef = "loginSqlSessionTemplate")
public class LoginDataSourceConfig {

    @Bean(name = "loginDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.login")
    @Primary//主数据源需声明@Primary注解
    public DataSource loginDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "loginSqlSessionFactory")
    @Primary
    public SqlSessionFactory loginSqlSessionFactory(@Qualifier("loginDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/login/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "loginTransactionManager")
    @Primary
    public DataSourceTransactionManager loginTransactionManager(@Qualifier("loginDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "loginSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate loginSqlSessionTemplate(@Qualifier("loginSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}